package com.bloveoa.zkkd.service.impl;

import com.bloveoa.zkkd.doman.LockedTokenModel;
import com.bloveoa.zkkd.doman.UserModel;
import com.bloveoa.zkkd.repository.LockedTokenRepository;
import com.bloveoa.zkkd.repository.UserRepository;
import com.bloveoa.zkkd.service.LockedTokenService;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.Date;
import java.util.List;

@Service
public class LockedTokenServiceImpl implements LockedTokenService {

    private final LockedTokenRepository lockedTokenRepository;
    private final UserRepository userRepository;

    public LockedTokenServiceImpl(LockedTokenRepository outTokenRepository, UserRepository userRepository) {
        this.lockedTokenRepository = outTokenRepository;
        this.userRepository = userRepository;
    }

    @Override
    @Transactional
    public LockedTokenModel insertLockedToken(LockedTokenModel tokenModel) {
        LockedTokenModel save = lockedTokenRepository.save(tokenModel);
        UserModel userModel = userRepository.queryById(Integer.valueOf(tokenModel.getUserId()));
        userModel.setLockedNum(tokenModel.getLockedTokenNum());
        userModel.setTokenNum(userModel.getTokenNum()-userModel.getLockedNum());
        userRepository.save(userModel);
        return save;
    }

    @Override
    public LockedTokenModel saveLockedToken(LockedTokenModel tokenModel) {
        return lockedTokenRepository.save(tokenModel);
    }

    @Override
    public List<LockedTokenModel> findAllByFlagDelete(Boolean flagDelete) {
        return lockedTokenRepository.findAllByFlagDelete(flagDelete);
    }

    @Override
    public List<LockedTokenModel> findAllByFlagDeleteIsFalseAndLockEndTimeBefore(Date endTime) {
        return lockedTokenRepository.findAllByFlagDeleteIsFalseAndLockEndTimeBefore(endTime);
    }
}
